<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <script>
      //树结构平铺成一维数组
      const treeData = [
        {
          id: 'p1',
          title: '广东',
          children: [
            {
              id: 'p1-1',
              title: '广州',
            },
          ],
        },
        {
          id: 'p2',
          title: '四川',
          children: [
            {
              id: 'p2-1',
              title: '成都',
              children: [
                {
                  id: 'p2-1-1',
                  title: '高新区',
                },
              ],
            },
            {
              id: 'p2-2',
              title: '德阳',
            },
            {
              id: 'p2-3',
              title: '绵阳',
            },
          ],
        },
      ];

      //平铺树的方法
      const flatTree = (tree) => {
        //平铺的数组
        const flatArray = [];
        //平铺的方法
        const flat = (node) => {
          //将节点添加到flatArray中
          flatArray.push(node);
          //对树中的每个子节点递归
          if (node.children) {
            node.children.forEach((node) => {
              flat(node);
            });
          }
        };

        //递归的方式遍历每个节点
        tree.forEach((node) => {
          flat(node);
        });
        return flatArray;
      };
      const flatTreeData = flatTree(treeData);

      console.log('flatTreeData', flatTreeData);
    </script>
  </body>
</html>
